import { BlockEnum, NodePanelProps } from '@/components/workflow/types'
import KnowledgeDia from '@/pages/ApplicationEditPage/components/KnowledgeDia'
import { INPUT_CONSTRAINTS } from '@/pages/workflow/components/InspectData'
import { variableSourceTypeOptions } from '@/pages/workflow/constants'
import { useWorkFlowStore } from '@/store/workflowStore'
import { CaretRightOutlined } from '@ant-design/icons'
import { Collapse, Input, Select } from 'antd'
import { produce } from 'immer'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import ListComponent from '../../components/ListItem'
import { ComponentDescMap } from '../../constants'
import { useSourceOptions } from '../../hooks/use-source-options'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import RunDrawer from '../components/RunDrawer'
import TempNodeOutput from '../components/TempNodeOutput'
import '../style.less'
import { KnowledgeNodeType, getKnowledgeInputListParams } from './default'

const KnowledgePanel: FC<NodePanelProps<KnowledgeNodeType>> = ({ id, data }) => {
  const { flowVariables, setFlowVariables } = useWorkFlowStore()
  const { options: citeOptions } = useSourceOptions(data)
  const [queryInfo, setQueryInfo] = useState(
    data.inputList && data.inputList.length > 0 
      ? {
          ...data.inputList[0],
          value: data.inputList[0].valuet || data.inputList[0].value,
          value_selector:  data.inputList[0].value_selector ?  data.inputList[0].value_selector : ( data.inputList[0].valuet  ?   data.inputList[0].valuet.split(',') : undefined),
        }
      : getKnowledgeInputListParams()
  )

  const [knowledgeOpen, setKnowledgeOpen] = useState(false)
  const [knowledgeList, setKnowledgeList] = useState(data.knowledgeList || [])
  /* 新增 */
  const addFile = data => {
    const newFileInfo = { id: data.id, icon: data.icon, name: data.name, description: data.description }
    setKnowledgeList([...knowledgeList, newFileInfo])
    setFlowVariables(id, data.title, { knowledgeList: [...knowledgeList, newFileInfo] })
  }
  const removeFile = fileId => {
    const filteredList = knowledgeList.filter(t => t.id !== fileId)
    setKnowledgeList([...filteredList])
    setFlowVariables(id, data.title, { knowledgeList: [...filteredList] })
  }

  const handleTypeChange = (value: any) => {
    const newPayload = produce(queryInfo, draft => {
      draft.type = value
      draft.value = undefined
      draft.value_selector = undefined
      draft.valuet = undefined
    })
    setQueryInfo(newPayload)
    setFlowVariables(id, data.title, { inputList: [newPayload] })
  }

  const handleCiteValChange = (value: any) => {
    const newPayload = produce(queryInfo, draft => {
      draft.value = value
      draft.value_selector = value.split(',')
      draft.valuet = value
    })
    setQueryInfo(newPayload)
    setFlowVariables(id, data.title, { inputList: [newPayload] })
  }
  const handleValueChange = (value: any) => {
    const newPayload = produce(queryInfo, draft => {
      draft.value = value
    })
    setQueryInfo(newPayload)
    setFlowVariables(id, data.title, { inputList: [newPayload] })
  }

  // 单节点运行

  const [runDrawerHid, setrunDrawerHid] = useState(false)

  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      /* 单节点运行弹窗 */
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }
    }
  }, [flowVariables])

  return (
    <div className="workflow-common-panel">
      <div className="common-panel-desc">{data.desc || ComponentDescMap[BlockEnum.End]}</div>

      <div className="nodrag cursor-default" draggable="false">
        <div className="nodrag cursor-default">
          <Collapse
            bordered={false}
            defaultActiveKey={['1']}
            expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
            className="bg-[#fafafa]"
            items={[
              {
                key: '1',
                label: (
                  <CollapseNodeComponent
                    title="输入"
                    tooltipText="输入需要从知识库里匹配的关键信息"
                  ></CollapseNodeComponent>
                ),
                children: (
                  <>
                    <div className="ml-[1px] flex">
                      <div className="input-head w-[32%]">参数名称</div>
                      <div className="input-head w-[28%]">参数值</div>
                    </div>
                    <div className="flexRowStart flexRowJustBet mt-[8px]">
                      <div className="flexRowStart flexRowJustBet w-[92%]">
                        <Input
                          value={queryInfo.variable}
                          defaultValue={queryInfo.variable}
                          placeholder="输入参数名"
                          className="w-[140px]"
                          disabled
                          // onChange={e => {
                          //   const newValue = e.target.value
                          //   if (
                          //     newValue.length <= INPUT_CONSTRAINTS.NAME_MAX_LENGTH &&
                          //     (newValue === '' || /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(newValue))
                          //   ) {
                          //     handlePayloadChange('variable')(newValue)
                          //   }
                          // }}
                          draggable="false"
                        />
                        <div style={{ width: 'calc(100% - 140px)' }}>
                          <Select
                            defaultValue={queryInfo.type}
                            placeholder="请选择"
                            placement="bottomLeft"
                            style={{ width: '40%', pointerEvents: 'auto' }}
                            onChange={val => handleTypeChange(val)}
                            options={variableSourceTypeOptions}
                          ></Select>
                          {queryInfo.type === 'cite' ? (
                            <Select
                              defaultValue={queryInfo.value}
                              placeholder="请选择"
                              placement="bottomLeft"
                              style={{ width: '60%', pointerEvents: 'auto' }}
                              onChange={val => handleCiteValChange(val)}
                              options={citeOptions}
                            ></Select>
                          ) : (
                            <Input
                              defaultValue={queryInfo.value}
                              placeholder="输出参数值"
                              style={{ width: '60%' }}
                              maxLength={INPUT_CONSTRAINTS.DESCRIPTION_MAX_LENGTH}
                              onChange={e => handleValueChange(e.target.value)}
                            />
                          )}
                        </div>
                      </div>
                    </div>

                    {!queryInfo.value && <div className="custom-params-invalid">参数值不能为空</div>}
                  </>
                )
              }
            ]}
          />
        </div>
        <div className="mt-[8px]">
          <Collapse
            bordered={false}
            defaultActiveKey={['2']}
            expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
            className="bg-[#fafafa]"
            items={[
              {
                key: '2',
                label: (
                  <CollapseNodeComponent
                    title="知识库"
                    tooltipText="选择需要匹配的知识库，仅从选定的知识库中召回信息"
                    right={
                      <div className="cursor-pointer" onClick={e => e.stopPropagation()}>
                        <svg
                          width="14"
                          className="mr-2 text-primary hover:text-primary/80"
                          height="14"
                          viewBox="0 0 14 14"
                          onClick={() => {
                            setKnowledgeOpen(true)
                          }}
                          fill="none"
                          xmlns="http://www.w3.org/2000/svg"
                        >
                          <path
                            d="M7 2L7 12"
                            stroke="#5964F3"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                          <path
                            d="M2 7L12 7"
                            stroke="#5964F3"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                      </div>
                    }
                  ></CollapseNodeComponent>
                ),
                children: (
                  <>
                    <div className="flexCol mb-[0px]">
                      {knowledgeList.map((item: any) => (
                        <ListComponent
                          key={item.id}
                          item={item}
                          clickCallBack={() => {
                            window.open(`/filelib/${item.id}`, '_blank', 'noreferrer')
                          }}
                          delCallBack={id => {
                            removeFile(id)
                          }}
                        />
                      ))}

                      {!knowledgeList || knowledgeList.length === 0 ? (
                        <div className="custom-params-invalid">知识库不能为空</div>
                      ) : (
                        <></>
                      )}
                      {knowledgeList && knowledgeList.length > INPUT_CONSTRAINTS.KNOWLEDGE_MAX_CONT ? (
                        <div className="custom-params-invalid">知识库数量不能大于20</div>
                      ) : (
                        <></>
                      )}
                    </div>
                    {/* {!outputText?.length && (
                      <div className="custom-params-invalid">{`直接使用指定内容回答时，输出内容不能为空`}</div>
                    )}
                    {outputText.length > INPUT_CONSTRAINTS.AGENT_RECOVERY_MAX_LENGTH && (
                      <div className="custom-params-invalid">{`输出内容不能大于${INPUT_CONSTRAINTS.AGENT_RECOVERY_MAX_LENGTH}个字符`}</div>
                    )} */}
                  </>
                )
              }
            ]}
          />
        </div>
        <div className="mt-[8px]">
          <Collapse
            bordered={false}
            defaultActiveKey={['3']}
            expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
            className="bg-[#fafafa]"
            items={[
              {
                key: '3',
                label: (
                  <CollapseNodeComponent
                    title="输出"
                    tooltipText="输出列表，是所选知识库里与输入参数最匹配的召回信息"
                  ></CollapseNodeComponent>
                ),
                children: <TempNodeOutput outputList={data.outputList}></TempNodeOutput>
              }
            ]}
          />
        </div>
      </div>

      {knowledgeOpen && (
        <KnowledgeDia
          knowledge_list={knowledgeList}
          addFile={addFile}
          open={knowledgeOpen}
          setOpen={setKnowledgeOpen}
        ></KnowledgeDia>
      )}

      {runDrawerHid && <RunDrawer nodeData={data} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}
    </div>
  )
}

export default React.memo(KnowledgePanel)
